// pages/courseware/courseware.js
var base = require('../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数

const PAGES = require('../../utils/pages.js')
const { getUserToken, getUserInfo, getIsLogin } = require('../../lib/user.js')
const { URL } = require('../../lib/urls.js')
const { HTTP } = require('../../lib/http.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    typeArry: [],
    nameArry: [],
    isFromSearch: true, // 用于判断searchSongList数组是不是空数组，默认true，空的数组
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次
    callbackcount: 6,   //返回数据的个数
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isShowNullView: false,
    nowIndex: 0,//当前选中code
    dataList: [],
    bannerInfos:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
    if (!getIsLogin()) {
      wx.navigateTo({
        url: PAGES.index,
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //处理tab重复
    wx.hideTabBar({
      fail: function () {
        setTimeout(function () {
          wx.hideTabBar()
        }, 500)
      }
    });
    //处理tab重复
    this.getNetBannerList();//获取首页banner图
    this.getNetTypeList();
    this.fetchDataList();
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.getCartCount();
  },

  //标签点击事件
  onSelectEvent: function (e) {
    const index = e.detail.currentTarget.dataset.index;
    if (this.data.nowIndex == index) {
      return;
    }
    this.setData({
      nowIndex: index,
      isFromSearch: true,
      searchPageNum: 1,
      searchLoading: false,
      searchLoadingComplete: false,
    })
    this.getNetTypeList();
    this.fetchDataList();
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      searchPageNum: 1,  //每次触发上拉事件，把searchPageNum+1
      isFromSearch: true  //触发到上拉事件，把isFromSearch设为为false
    });
    that.fetchDataList();
  },
  //滚动到底部触发事件
  onReachBottom: function () {
    let that = this;
    if (that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1,  //每次触发上拉事件，把searchPageNum+1
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false
      });
      that.fetchDataList();
    }
  },
  //获取分类列表
  getNetTypeList: function () {
    let that = this;
    HTTP({
      url: URL.courseware.coursewareType,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        var listName = [], list = [];
        listName.push(_('全部'));
        var all = { TypeCode:""};
        list.push(all);
        for (var i = 0; i < res.VideoTypeInfos.length; i++) {
          var model = res.VideoTypeInfos[i];
          listName.push(model.Name);
          list.push(model);
        }
        that.setData({
          nameArry: listName,
          typeArry: list,
        });
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //获取课程列表
  fetchDataList: function () {
    wx.showLoading({
      title: '加载中...'
    })
    let that = this;
    let searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数
      callbackcount = that.data.callbackcount; //返回数据的个数
    let selecModel=this.data.typeArry[this.data.nowIndex];

    HTTP({
      url: URL.courseware.coursewareList,
      userToken: getUserToken(),
      data: {
        Code: selecModel ? selecModel.TypeCode:'',
        PageIndex: searchPageNum,
        PageSize: callbackcount,
      },
      success: (ress) => {
        wx.stopPullDownRefresh();
        wx.hideLoading();
        var res = ress.Data;
        if (res.VideoCourseInfos.length > 0) {
          console.log("hlw:" + res)
          let searchList = [];
          var list = [];
          for (var i = 0; i < res.VideoCourseInfos.length; i++) {
            var model = res.VideoCourseInfos[i];
            if (model) {
              list.push(model);
            }
          }
          //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
          this.data.isFromSearch ? searchList = list : searchList = that.data.dataList.concat(list)
          this.setData({
            dataList: searchList, //获取数据数组
            searchLoading: true,   //把"上拉加载"的变量设为false，显示
            isShowNullView: searchList.length > 0 ? false : true
          });
          if (res.VideoCourseInfos.length < callbackcount) {
            //数据已加载完毕
            that.setData({
              searchLoadingComplete: true, //把“没有数据”设为true，显示
              searchLoading: false  //把"上拉加载"的变量设为false，隐藏
            });
          }
          //没有数据了，把“没有数据”显示，把“上拉加载”隐藏
        } else {
          if (that.data.searchPageNum == 1) {
            that.setData({
              dataList: [],
              isShowNullView: true
            })
          }
          that.setData({
            searchLoadingComplete: true, //把“没有数据”设为true，显示
            searchLoading: false  //把"上拉加载"的变量设为false，隐藏
          });
        }
      }, fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //获取首页轮播图
  getNetBannerList: function () {
    var that = this;
    HTTP({
      url: URL.home.sysBannerList,
      userToken: getUserToken(),
      data: {
        MemberId: getUserInfo().memberId,
        BannerType:2,//视频banner
      },
      success: (ress) => {
        var res = ress.Data;
        if (res.SysBannerInfos.length > 0) {
          that.setData({
            bannerInfos: res.SysBannerInfos,
          })
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //跳转到课程详情
  onItemTap: function (e) {
    var data = JSON.stringify(e.currentTarget.dataset.item);
    wx.navigateTo({
      url: PAGES.coursewareInfo + '?data=' + encodeURIComponent(data),
    });
  },

  //获取购物车商品数量
  getCartCount: function () {
    let that = this;
    HTTP({
      url: URL.goods.cartCount,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        var list = [];
        for (var i in that.getTabBar().data.list) {
          var model = that.getTabBar().data.list[i];
          if (i == 2) {
            model.tagNum = res;
          }
          list.push(model);
        }
        that.getTabBar().setData({
          list: list
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
})